package com.zhny.iot.okq.insect.pest.plugin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.plugin.web.WebDevice;
import com.zhny.iot.okq.insect.pest.plugin.response.Result;
import io.netty.util.internal.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

public class OKQDevice extends WebDevice<OKQConfig> {
    private static final Logger log = LoggerFactory.getLogger(OKQDevice.class);
    public OKQDevice(IDeviceFactory<OKQConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (factory, centerFacilities, entity);
    }

    @Override
    protected void onRequestHttp(TaskEntity taskEntity, CloseableHttpClient closeableHttpClient) {
        log.info ("execute okq insect pest api request!");
        if(onGetDeviceList(closeableHttpClient))
            onInsectPestResponse(closeableHttpClient);
    }


    private boolean onGetDeviceList(CloseableHttpClient httpClient) {
        URIBuilder uriBuilder=null;
        OKQConfig config=this.getConfig ();

        try {
            String httpUrl="http://nyzbwlw.com/situation/http/device/equipment/getEquipmentList";
            uriBuilder=new URIBuilder (httpUrl);
            uriBuilder.addParameter ("userName", config.getUsername ());
            uriBuilder.addParameter ("passWord", config.getPassword ());
            HttpGet httpGet=new HttpGet (uriBuilder.build ());
            try (CloseableHttpResponse response =httpClient.execute (httpGet) ){
                String body =EntityUtils.toString (response.getEntity ());
                Result<Map<String,Object>> result = deserialize (body, new TypeReference<Result<Map<String,Object>>> () {
                });
                if(result == null){
                    log.error ("{}okq insect pest get device list api result map to error !",this.getDeviceEntity ().getName ());return false;}
                log.info ("find insect pest device list success");
                return true;
            }catch (ClientProtocolException e) {
                throw new RuntimeException (e);
            } catch (ConnectTimeoutException e) {
                throw new RuntimeException("请求连接超时");
            } catch (IOException e) {
                throw new RuntimeException (e);
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException (e);
        }
    }
    private void onInsectPestResponse(CloseableHttpClient httpClient) {
        URIBuilder uriBuilder=null;
        OKQConfig config=this.getConfig ();
        try {
            String httpUrl="http://nyzbwlw.com:204/situation/http/device/bug/getBugData";
            uriBuilder=new URIBuilder (httpUrl);
            uriBuilder.addParameter ("deviceCode", config.getSn ());
            HttpGet httpGet=new HttpGet (uriBuilder.build ());
            try (CloseableHttpResponse response =httpClient.execute (httpGet) ){
                String body =EntityUtils.toString (response.getEntity ());
                Result<Map<String,Object>> result = deserialize (body, new TypeReference<Result<Map<String,Object>>> () {
                });
                if(result == null){
                    log.error ("{}okq insect pest data api result map to error !",this.getDeviceEntity ().getName ());return;}
                onSetMap (result.getData ());
            }catch (ClientProtocolException e) {
                throw new RuntimeException (e);
            } catch (ConnectTimeoutException e) {
                throw new RuntimeException("请求连接超时");
            } catch (IOException e) {
                throw new RuntimeException (e);
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException (e);
        }
    }

    private void onSetMap(Map<String, Object> data) {
        if(!data.containsKey ("list"))
            return;
        if(data.get ("list") == null)
            return;
        if(data.get ("list") instanceof List){
            List<Map<String,Object>> list=(List<Map<String,Object>>)data.get ("list");
            if(list == null || list.size () == 0)
                return;
            MessageEntry messageEntry=MessageUtils.createMessageEntry (this.getId ());
            messageEntry.setType (MessageType.RESULT);
            InsectPestStoreEntry entry = new InsectPestStoreEntry ();
            Map<String,Object> index1 = list.get (0);
            entry.setNum (index1.get ("num").toString ());
            entry.setUrl (index1.get ("pictureUrl").toString ());
            messageEntry.setData (entry);
            save (entry);
            nofity (messageEntry);
        }
    }

    public <T> T deserialize(String json, TypeReference<T> typeReference) {
        if(StringUtil.isNullOrEmpty (json))
            return null;
        ObjectMapper mapper=new ObjectMapper ();
        try {
            mapper.configure (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            T obj=mapper.readValue (json, typeReference);
            return obj;
//            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            return null;
        }
    }
}
